package com.xiaoshuai.plat.controller;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xiaoshuai.plat.service.CoreService;
import com.xiaoshuai.plat.util.weixin.SignUtil;

/**
 * 回调配置
 * @author 宗潇帅
 * @Title WXConfigController
 * @时间   2017-1-4上午11:06:05
 */
@Controller
@RequestMapping(value="/wxconfig")
public class WXConfigController {
	private static Logger logger = Logger.getLogger(WXConfigController.class);
	
	@RequestMapping(value="/valid",method={RequestMethod.GET},produces = "application/json;charset=UTF-8")
	public void valid(HttpServletRequest request,HttpServletResponse response,PrintWriter out) throws Exception{
		System.out.println("回调请求=======================");
		//微信加密签名
		String signature = request.getParameter("signature");
		//时间戳
		String timestamp = request.getParameter("timestamp"); 
		//随机数
		String nonce = request.getParameter("nonce");
		//随机字符串
		String echostr = request.getParameter("echostr");
		out = response.getWriter();
		//通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败 
		if(SignUtil.checkSignature(signature, timestamp, nonce)){
			out.print(echostr);
		}else{
			System.out.println("非微信发送的GET请求");
		}
		logger.info("回调请求发送的参数为signature"+signature+"\n"+"timestamp"+timestamp+"\n"+"nonce"+nonce+"\n"+"echostr"+echostr);
		out.flush();
		out.close();
	}
	@RequestMapping(value="/valid",method={RequestMethod.POST},produces = "application/json;charset=UTF-8")
	public void infos(HttpServletRequest request,HttpServletResponse response,PrintWriter out) throws Exception{
        /* 消息的接收、处理、响应 */  
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");  
        CoreService coreService = new CoreService();
        // 调用核心业务类接收消息、处理消息  
        String respMessage = coreService.processRequest(request);  
        logger.info(respMessage);  
        // 响应消息  
        out = response.getWriter();  
        out.print(respMessage);  
        out.close(); 
	}
}